import java.io.IOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

/**
 * 回显服务器  服务端
 *
 */
public class UDPEchoSever {
    //声明服务端对象
    private DatagramSocket socket;

    //构造端口号  创建服务端对象
    public UDPEchoSever(int port) throws SocketException {
        if(port < 1024 || port > 65535) {
            throw new BindException("端口号异常..");
        }
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器已经创建...");
        //循环处理用户发来的数据
        while (true) {
            //创建接受用户数据的对象
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            //使用服务端接收 用户数据对象
            socket.receive(requestPacket);
            //解析数据
            String request = new String(requestPacket.getData(), 0,
                    requestPacket.getLength(), "UTF-8");
            //通过计算得到请求
            String response = process(request);
            //再次封装数据
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),
                    0,request.getBytes().length,requestPacket.getSocketAddress());
            //发送响应
            socket.send(responsePacket);
            //打印日志 格式化输出
            System.out.printf("[%s:%d] request = %s, response = %s\n",
                    requestPacket.getAddress().toString(), requestPacket.getPort(),request,response);
        }
    }

    protected String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UDPEchoSever udpEchoSever = new UDPEchoSever(8888);
        udpEchoSever.start();
    }
}
